<template>
	<el-form ref="formRef" :model="password" :rules="rules" :label-width="80">
		<el-form-item :label="t('profile.password.oldPassword')" prop="oldPassword">
			<InputPassword v-model="password.oldPassword"/>
		</el-form-item>
		<el-form-item :label="t('profile.password.newPassword')" prop="newPassword">
			<InputPassword v-model="password.newPassword" strength/>
		</el-form-item>
		<el-form-item :label="t('profile.password.confirmPassword')" prop="confirmPassword">
			<InputPassword v-model="password.confirmPassword" strength/>
		</el-form-item>
		<el-form-item style="text-align: center">
			<div class="fromSave"  @click="submit(formRef)">{{ t('common.save') }}</div>
		</el-form-item>
	</el-form>
</template>
<script lang="ts" setup>
import type {FormInstance, FormRules} from 'element-plus'

import {InputPassword} from '@/components/InputPassword'
import {updateUserPassword} from '@/api/system/user/profile'

defineOptions({name: 'ResetPwd'})

const {t} = useI18n()
const message = useMessage()
const formRef = ref<FormInstance>()
const password = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单校验
const equalToPassword = (_rule, value, callback) => {
  if (password.newPassword !== value) {
    callback(new Error(t('profile.password.diffPwd')))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  oldPassword: [
    {required: true, message: t('profile.password.oldPwdMsg'), trigger: 'blur'},
    {min: 6, max: 20, message: t('profile.password.pwdRules'), trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: t('profile.password.newPwdMsg'), trigger: 'blur'},
    {min: 6, max: 20, message: t('profile.password.pwdRules'), trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: t('profile.password.cfPwdMsg'), trigger: 'blur'},
    {required: true, validator: equalToPassword, trigger: 'blur'}
  ]
})

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await updateUserPassword(password.oldPassword, password.newPassword)
      message.success(t('common.updateSuccess'))
    }
  })
}

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped lang="scss">
$wh: 40px;

.fromSave {
  $h: 36px;
  width: 96px;
  height: $h;
	line-height: $h;
  background: #0D0D0D;
  text-align: center;
  
  font-weight: 400;
  font-size: 14px;
  color: #FFFFFF;
}

:deep(.el-form-item--default .el-form-item__label) {
  height: $wh;
  line-height: $wh;
}

:deep(.el-input) {
  width: 360px;
  height: $wh;
}
</style>